package etnorservice.etnor_service.service;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2025/02/27/12:19
 **/

import etnorservice.etnor_service.config.UploadConfig;
import etnorservice.etnor_service.domain.dto.ImageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

@Service
public class ImageService {

    @Autowired
    private UploadConfig uploadConfig;

    @Autowired
    private RestTemplate restTemplate;

    public ImageResponse uploadImage(MultipartFile file, Integer permission, Integer strategyId, Integer albumId) throws Exception {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        if (uploadConfig.getToken() != null) {
            System.out.println("图床token======》"+uploadConfig.getToken());
            headers.set("Authorization", "Bearer " + uploadConfig.getToken());
        }
        headers.set("Accept", "application/json");

        // 准备请求体
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        ByteArrayResource fileResource = new ByteArrayResource(file.getBytes()) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }
        };

        body.add("file", fileResource);
        body.add("permission", permission);
        if (strategyId != null) {
            body.add("strategy_id", strategyId);
        }
        if (albumId != null) {
            body.add("album_id", albumId);
        }

        // 发送请求
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        ResponseEntity<ImageResponse> response = restTemplate.exchange(
                uploadConfig.getBaseUrl() + uploadConfig.getUploadPath(),
                HttpMethod.POST,
                requestEntity,
                ImageResponse.class
        );

        return response.getBody();
    }
}
